<!--
  * 商品明细
  *
-->
<template>
  <div>
    <a-table :dataSource="tableData" :columns="columns" :scroll="{ x: 'max-content' }" :pagination="false" rowKey="id" size="small" bordered>
      <template #bodyCell="{ text, record, column, index }">
        <template v-if="column.dataIndex === 'purchase_total_price'"> {{ text }}</template>
        <template v-if="column.dataIndex.startsWith('第')">
          {{ record[column.dataIndex] }}
        </template>
      </template>
    </a-table>
  </div>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message } from 'ant-design-vue'
const props = defineProps({
  enterpriseId: {
    type: Array,
    default: null
  }
})

const columns = ref([
  {
    title: '商品编号',
    dataIndex: 'goods_no'
  },
  {
    title: '商品/现金',
    dataIndex: 'name'
  },
  {
    title: '规格属性',
    dataIndex: 'spec'
  },
  {
    title: '单位',
    dataIndex: 'unit'
  },
  {
    title: '条码',
    dataIndex: 'bar_code'
  },
  {
    title: '总计',
    dataIndex: 'purchase_total_price',
    width: 150
  }
])

const tableData = ref([])

const showData = (e) => {
  tableData.value = e.detail
    ? e.detail.map((item) => {
        const rewardSet = item.reward_set || []
        const months = {}
        rewardSet.forEach((monthData) => {
          // const monthKey = Object.keys(monthData)[0]
          // months[monthKey] = monthData[monthKey]
          months[monthData.cycle_date] = monthData.cycle_num
        })
        return {
          ...item,
          ...months,
          reward_set: rewardSet // 保留原始 reward_set 数据
        }
      })
    : []
  // 计算每条记录的总计
  tableData.value.forEach((item) => {
    calculateTotal(item)
  })
  updateColumns()
}

// 新增月份
function updateColumns() {
  const monthCount = parseInt(props.enterpriseId.display_cycle, 10)
  if (monthCount <= 0) {
    message.error('陈列周期格式不正确')
    return
  }

  // 清空旧的月份列
  columns.value = columns.value.filter((col) => !col.dataIndex.startsWith('第'))

  // 添加新的月份列
  const newColumns = Array.from({ length: monthCount }, (_, index) => ({
    title: `第${index + 1}月`,
    dataIndex: `第${index + 1}月`,
    width: 150
  }))

  // 插入月份列到“总计”列之前
  const totalIndex = columns.value.findIndex((col) => col.dataIndex === 'purchase_total_price')
  columns.value.splice(totalIndex, 0, ...newColumns)
}

// 总计
function calculateTotal(record) {
  let total = 0
  const monthCount = parseInt(props.enterpriseId.display_cycle, 10)
  for (let i = 1; i <= monthCount; i++) {
    const monthKey = `第${i}月`
    if (record[monthKey]) {
      total += record[monthKey]
    }
  }
  record.purchase_total_price = total
}
watch(
  () => props.enterpriseId,
  (e) => {
    if (e) {
      showData(e)
    }
  },
  { immediate: true }
)
</script>

<style scoped lang="less">
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 20px 0;
}

.button-style {
  margin: 0 10px;
}
</style>
